package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.List;
import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.NoticeAdapter;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.ArtistWorkInfoParse;
import artid.com.arttogoa.parser.AuthcertificationItem;
import artid.com.arttogoa.parser.NoiceListParser;
import artid.com.arttogoa.parser.UpdataSystemMessageParser;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullableListView;
import artid.com.arttogoa.view.pulltorefresh.pullableview.PullToRefreshLayout.OnRefreshListener;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：NoticeActivity   
 * 类描述：通知列表页   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午2:28:42      
 *
 */
public class NoticeActivity extends BaseActivity implements OnClickListener {
	private PullableListView mListView;
	private NoticeAdapter adapter;
	private Context mContext;
	private boolean isRefreshed = false;// 是否刷新
	private int page=1;
	private List<NoiceListParser> list;
	private List<NoiceListParser> more_list;
	private PullToRefreshLayout mPullLayout;
	private LinearLayout noDataLL;
	private int OnClicItemPosition=-1;//点击的Item下标

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_notice);
		setContent(this, getIntent());
		ArtWorkApp.getInstance().addActivity(this);
		//注册当前广播
		IntentFilter filter = new IntentFilter("com.Push.receiver");  
		registerReceiver(broadcastReceiver, filter);  
		mContext = this;
		list=new ArrayList<NoiceListParser>();
		more_list=new ArrayList<NoiceListParser>();
		mTittle = (TextView) findViewById(R.id.title_text);
		mTittle.setText("通知列表");
		setBack();
		noDataLL=(LinearLayout) findViewById(R.id.Notice_noData);
		mListView =(PullableListView) findViewById(R.id.Notice_listivew);
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				/*最初实现
				Intent in = new Intent(NoticeActivity.this,NoticeDetailActivity.class);
				in.putExtra("id", more_list.get(position).getId());
				startActivity(in);
				 */
				Intent intent;
				OnClicItemPosition=position;
				if("1".equals(more_list.get(position).getType())){
					//判断是否为系统消息
					intent=new Intent(mContext,BaseWebView_Activity.class);
					intent.putExtra("titleName", "系统消息");
					intent.putExtra("webURL", more_list.get(position).getMessurl());
					intent.putExtra("type", "systemWebView");
					intent.putExtra("messageID", more_list.get(position).getMessid());
					startActivity(intent);
				}else if("2".equals(more_list.get(position).getType())){
					//判断是否为订单消息
					String title=more_list.get(position).getTitle();
					intent=new Intent(mContext,OrderInfo_Activity.class);
					if("已付款".equals(title)){
						intent .putExtra("whichActivity", 1);
					}else if("已收货".equals(title)){
						intent .putExtra("whichActivity", 4);
					}
					intent .putExtra("order_id", more_list.get(position).getMessid());
					intent.	putExtra("isPush", true);
					startActivity(intent);
				}else if("4".equals(more_list.get(position).getType())){
					requestAutoStatus(more_list.get(position).getMessid());
				}else{
					showToast("该条消息已过期");
				}
			}
		});
		mPullLayout = (PullToRefreshLayout)findViewById(R.id.Notice_refresh_view);
		mPullLayout.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				//下拉刷新
				page=1;
				isRefreshed=true;
				getNoiceList();
			}

			@Override
			public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
				// TODO Auto-generated method stub
				// pullToRefreshLayout.setBottomDismiss();
				//加载更多
				page++;
				getNoiceList();
			}
		});
		getNoiceList();
	}

	@Override
	public void onClick(View v) {
	}

	/**
	 * 获取通知列表
	 */
	private void getNoiceList(){
		VolleyBasic.getInstance(NoticeActivity.this).post(Cache.noiceList,
				VolleyMap.getInstance().noiceList(page,10), NoiceListParser.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				mPullLayout.loadmoreFinish(mPullLayout.SUCCEED);
				list=(List<NoiceListParser>) vd.getList();
				if (isRefreshed == true) {
					more_list.clear();
					isRefreshed = false;
				}
				if (!list.isEmpty()) {
					more_list.addAll(list);
				}
				if(more_list!=null && more_list.size()!=0){
					noDataLL.setVisibility(View.GONE);
				}else{
					noDataLL.setVisibility(View.VISIBLE);
					return;
				}
				if (adapter == null) {
					adapter=new NoticeAdapter(mContext, more_list);
					mListView.setAdapter(adapter);
				}
				adapter.notifyDataSetChanged();
				Log.d("log", more_list.toString());
			}
			public void onError(VolleyError volleyError) {
				mPullLayout.loadmoreFinish(mPullLayout.FAIL);
			}
		});
	}

	/**
	 * 获取审核信息
	 */
	private void requestAutoStatus(final String messageID) {
		VolleyBasic.getInstance(NoticeActivity.this).post(Cache.authcertification,
				VolleyMap.getInstance().authCertification(),
				AuthcertificationItem.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				AuthcertificationItem item = (AuthcertificationItem) vd.getData();
				String status = item.getIs_auth();
				if (status.equals("-1")) {
					//未通过
					Intent intent=new Intent(mContext,RealNameAuthenticationActivity.class);
					intent.putExtra("isPush", true);
					intent.putExtra("messageID", messageID);
					startActivity(intent);
					updataSystmeMessage(messageID);
				}else {
					Intent intent=new Intent(mContext,RealNameAuthenticationTwoActivity.class);
					intent.putExtra("isPush", true);
					intent.putExtra("messageID", messageID);
					startActivity(intent);
				} 
			}
			@Override
			public void onError(VolleyError volleyError) {
			}
		});
	}
	
	/**
	 * 修改系统消息为已读
	 */

	private void updataSystmeMessage(String MessageId){
		VolleyBasic.getInstance(this).post(true,false,Cache.updateSystemread,
				VolleyMap.getInstance().updateSystemread(MessageId),UpdataSystemMessageParser.class,new VolleyCallback() {
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				UpdataSystemMessageParser bean=(UpdataSystemMessageParser) vd.getData();
				if("1".equals(bean.getStatus())){
					getArtistWorkInfo();
				}else if("0".equals(bean.getStatus())){
					//失败
					ToastUtil.toast(mContext, "修改消息状态失败");
				}
			}
			public void onError(VolleyError volleyError) {
			}
		});
	}

	/**
	 * 艺术家备案动态资讯数量和推送消息数量
	 */
	private void getArtistWorkInfo(){
		VolleyBasic.getInstance(this).post(false,true,Cache.artistWorkInfo,VolleyMap.getInstance().artistWorkInfo(),
				ArtistWorkInfoParse.class, new VolleyCallback() {
			@Override
			public void onSuccess(VolleyData vd) {
				Log.d("log", vd.toString());
				ArtistWorkInfoParse bean=(ArtistWorkInfoParse) vd.getData();
				if(bean!=null){
					AppUtil.getUser().setRecordnum(bean.getRecordnum());
					AppUtil.getUser().setTrendsnum(bean.getTrendsnum());
					AppUtil.getUser().setNewsnum(bean.getNewsnum());
					AppUtil.getUser().setIs_auth(bean.getIs_auth());
					MainActivity.isSystemPush=bean.getIs_pushread();
					Intent intent2 = new Intent("com.Push.receiver");  
					intent2.putExtra("UpMessageType", true);
					mContext.sendBroadcast(intent2);
				}
			}
			@Override
			public void onError(VolleyError volleyError) {

			}
		});
	}

	//广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  

		@Override  
		public void onReceive(Context context, Intent intent) {  
			// TODO Auto-generated method stub  
			if("0".equals(intent.getStringExtra("PushType"))){
				//只要不等于0就是回复推送
				adapter=null;
				page=1;
				isRefreshed=true;
				getNoiceList();
			}else if(intent.getBooleanExtra("UpMessageType", false)==true){
				//修改系统消息是否已读
				if(more_list!=null && more_list.size()!=0 && OnClicItemPosition!=-1){
					more_list.get(OnClicItemPosition).setRead("0");
					adapter.notifyData(more_list);
				}
			}
			//成功
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		//清空推送
		MainActivity.PushMessage=null;
		//关闭广播
		unregisterReceiver(broadcastReceiver);
	}
}
